<template>
  <div class="content-header">
    <h1>图书管理</h1>
  </div>
  <div class="app-container">
    <div class="box">
      <!-- 搜索区域 -->
      <div class="filter-container">
        <el-input 
          placeholder="图书名称搜索" 
          v-model="queryString" 
          style="width: 200px;" 
          class="filter-item"
          @keyup.enter="fetchData"
        />
        <el-button @click="fetchData">查询</el-button>
        <el-button type="primary" @click="setState('add', null)">新建</el-button>
      </div>

      <!-- 图书表格 -->
      <el-table 
        size="small" 
        current-row-key="id" 
        :data="pagedDataList" 
        stripe 
        highlight-current-row
      >
        <el-table-column type="index" align="center" label="序号"></el-table-column>
        <el-table-column prop="type" label="图书类别" align="center"></el-table-column>
        <el-table-column prop="name" label="图书名称" align="center"></el-table-column>
        <el-table-column prop="description" label="描述" align="center"></el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button 
              type="primary" 
              size="mini" 
              @click="setState('update', scope.row)"
            >
              编辑
            </el-button>
            <el-button 
              type="danger" 
              size="mini" 
              @click="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin-top: 20px;"
      ></el-pagination>

      <!-- 编辑/新增弹窗 -->
      <el-dialog
        title="编辑图书信息" 
        v-model="editDialogVisible"
        width="40%" 
        align-center
      >
        <el-form :model="editForm" label-width="100px">
          <el-form-item label="图书名称">
            <el-input v-model="editForm.name"></el-input>
          </el-form-item>
          <el-form-item label="图书类别">
            <el-input v-model="editForm.type"></el-input>
          </el-form-item>
          <el-form-item label="描述">
            <el-input v-model="editForm.description"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleEdit">保存</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from "vue";
import Mock from 'mockjs';

// 模拟图书数据（持久化存储）
const mockBooks = ref([]);
// 初始化 Mock 数据（若为空则生成）
if (!localStorage.getItem('mockBooks')) {
  const initialData = Mock.mock({
    'data|30': [
      {
        'id|+1': 1,
        type: 'Fiction',
        name: 'Book @id',
        description: 'Description for Book @id',
      },
    ],
  }).data;
  localStorage.setItem('mockBooks', JSON.stringify(initialData));
  mockBooks.value = initialData;
} else {
  mockBooks.value = JSON.parse(localStorage.getItem('mockBooks'));
}

// 响应式数据
const queryString = ref('');     // 搜索关键字
const currentPage = ref(1);      // 当前页码
const pageSize = ref(10);        // 每页条数
const total = ref(0);            // 总条数
const pagedDataList = ref([]);   // 分页后的数据
const editDialogVisible = ref(false); // 弹窗显隐
const editForm = reactive({      // 弹窗表单数据
  id: null,
  type: '',
  name: '',
  description: '',
});

// 初始化数据
onMounted(() => {
  fetchData();
});

// 获取数据（含搜索、分页）
const fetchData = () => {
  // 1. 搜索过滤
  const filtered = mockBooks.value.filter(item => 
    item.name.includes(queryString.value)
  );

  // 2. 分页处理
  total.value = filtered.length;
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  pagedDataList.value = filtered.slice(start, end);
};

// 监听搜索关键字变化
watch(queryString, () => {
  currentPage.value = 1; // 搜索后重置页码
  fetchData();
});

// 弹窗状态控制（新增/编辑）
const setState = (type, row) => {
  editDialogVisible.value = true;
  if (type === 'update') {
    // 编辑时赋值
    editForm.id = row.id;
    editForm.type = row.type;
    editForm.name = row.name;
    editForm.description = row.description;
  } else {
    // 新增时清空表单
    editForm.id = null;
    editForm.type = '';
    editForm.name = '';
    editForm.description = '';
  }
};

// 保存编辑/新增
const handleEdit = () => {
  if (editForm.id) {
    // 编辑：找到对应图书并更新
    const index = mockBooks.value.findIndex(item => item.id === editForm.id);
    if (index !== -1) {
      mockBooks.value[index] = { ...editForm };
    }
  } else {
    // 新增：生成唯一 ID 并添加
    const newId = Mock.Random.integer(100, 999);
    mockBooks.value.push({ ...editForm, id: newId });
  }
  // 持久化到 localStorage
  localStorage.setItem('mockBooks', JSON.stringify(mockBooks.value));
  // 关闭弹窗 + 刷新数据
  editDialogVisible.value = false;
  fetchData();
};

// 删除图书
const handleDelete = (id) => {
  // 过滤掉被删除的图书
  mockBooks.value = mockBooks.value.filter(item => item.id !== id);
  // 持久化 + 刷新数据
  localStorage.setItem('mockBooks', JSON.stringify(mockBooks.value));
  fetchData();
};

// 分页 - 每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchData();
};

// 分页 - 当前页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchData();
};
</script>

<style scoped>
.filter-container {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
</style>